package controller;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.RequestDispatcher;
import javax.servlet.Servlet;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import model.TaiKhoanM;
import dao.TaiKhoanD;

/**
 * Servlet implementation class LoginServlet
 */
@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private TaiKhoanD dao;
//	private CryptoLibrary code;
    
	/**
	 * @throws Exception
	 * @see HttpServlet#HttpServlet()
	 */
	public LoginServlet() throws Exception {
		super();
		this.dao = new TaiKhoanD();
		//this.code = new CryptoLibrary();
	}

	/**
	 * @see Servlet#destroy()
	 */
	public void destroy() {
		// TODO Auto-generated method stub
	}

	public void writeFileLog(String str){
		try {
			String path = new File(".").getCanonicalPath()+"/web/QLDT/log.txt";
            File file = new File(path);
            if (!file.exists()) {
               file.createNewFile();
            }
            FileWriter fw = new FileWriter(file.getAbsoluteFile(),true);
            BufferedWriter bw = new BufferedWriter(fw);
            bw.write(str);
            bw.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession(false);
		try {
			if (request.getParameter("action").equals("logout")) {
				String user = (String)session.getAttribute("user") ;
				String start = request.getParameter("s");
				String end = request.getParameter("e");
				String str = user + " - " + start + " - " + end + "\n";
				writeFileLog(str);
				
				session = request.getSession(true);
				session.setAttribute("user", "");
				session.setAttribute("pass", "");
				session.setAttribute("rule", "");
				session.invalidate();
				response.sendRedirect("index.jsp");
				return;
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=UTF-8");

		PrintWriter out = response.getWriter();

		try {
			String username = request.getParameter("username");
			String password = request.getParameter("password");
			TaiKhoanM tk = dao.getTenDangNhap(username);

			if (tk != null) {
				String u = tk.getTen_dang_nhap();
				String p = tk.getMat_khau();
				String qt = tk.getNhom_nguoi_dung();
				if (username.trim().equals(u.trim()) && password.trim().equals((p.trim()))) {
					HttpSession session = request.getSession(true);
					session.setAttribute("user", username);
					session.setAttribute("pass", password);
					session.setAttribute("rule", qt);
					response.sendRedirect("Admin.jsp");
				} else {
					request.setAttribute("error", "Tên đăng nhập hay mật khẩu không hợp lệ");
					RequestDispatcher view = request.getRequestDispatcher("Login.jsp");
					view.forward(request, response);
				}
			} else {
				request.setAttribute("error", "Tên đăng nhập hay mật khẩu không hợp lệ");
				RequestDispatcher view = request.getRequestDispatcher("Login.jsp");
				view.forward(request, response);
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		} finally {
			out.close();
		}
	}
}
